#[cfg(feature = "ssr")]
mod error;
#[cfg(feature = "ssr")]
mod login;
#[cfg(feature = "ssr")]
mod middleware;
#[cfg(feature = "ssr")]
pub use error::AuthError;
#[cfg(feature = "ssr")]
pub use login::login;
#[cfg(feature = "ssr")]
pub use middleware::*;
#[cfg(feature = "ssr")]
use server_fn::ServerFnError;
#[cfg(feature = "ssr")]
use shq_common::prelude::AuthType;
#[cfg(feature = "ssr")]
pub async fn get_user_context() -> anyhow::Result<UserContext> {
    use crate::auth::UserContext;
    use axum::extract::Extension;
    leptos_axum::extract()
        .await
        .and_then(|ext: Extension<UserContext>| Ok(ext.0))
        .or_else(|_e| {
            let err_msg="认证失败，请登录".to_string();
            leptos_axum::redirect("/login");
            Err(anyhow::anyhow!(err_msg))
        })
}
#[cfg(feature = "ssr")]
pub async fn get_user_context_with_auth(
    menu_id: u32,
    auth_type: AuthType,
) -> Result<UserContext, ServerFnError> {
    let user = get_user_context().await.or_else(|err| {
        leptos_axum::redirect("/login");
        Err(ServerFnError::new(format!("获取用户信息失败：{}", err)))
    })?;
    let user_perm = shq_pas_backend::get_auth_type(user.user_id, menu_id)
        .await
        .map_err(|e| {
            leptos_axum::redirect("/login");
            AuthError::InternalServerError(format!(
                "验证用户权限时，执行get_auth_type出错:{}",
                e.to_string()
            ))
        })?
        .ok_or(AuthError::NotPermitted(auth_type.clone()))?;
    let has_suth=match auth_type {
        AuthType::Select => !user_perm.auth_types.is_empty(),
        AuthType::Insert => user_perm.auth_types.iter().any(|t| *t == AuthType::Insert||*t == AuthType::Edit),
        AuthType::Delete => user_perm.auth_types.iter().any(|t| *t == AuthType::Delete||*t == AuthType::Edit),
        AuthType::Update => user_perm.auth_types.iter().any(|t| *t == AuthType::Update||*t == AuthType::Edit),
        AuthType::Edit => user_perm.auth_types.contains(&AuthType::Edit),
        AuthType::Import => user_perm.auth_types.contains(&AuthType::Import),
        AuthType::Export => user_perm.auth_types.contains(&AuthType::Export),
    };
    if !has_suth {
        return Err(AuthError::NotPermitted(auth_type).into());
    }
    Ok(user)
}
